package system

import (
	"context"
	"fmt"
	"gf-assistant/internal/common/consts"
	"gf-assistant/internal/common/factory"
	util2 "gf-assistant/internal/common/util"
	"gf-assistant/internal/system/parameter"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"reflect"
)

type LoginService struct {
	userDao string
}

func init() {
	loginService := LoginService{userDao: "system.UserDao"}
	factory.Put(reflect.TypeOf(loginService).String(), &loginService)
}
func (s *LoginService) Login(ctx context.Context, userName string, password string) (msg string, data *parameter.LoginRes, err error) {
	loginUserDO := factory.Get(s.userDao).(*UserDao).GetUserByUserName(ctx, userName)
	if loginUserDO == nil {
		return "用户名或密码错误", data, nil
	}
	pwd := util2.EncryptHash256(loginUserDO.PwdSalt, password)
	if loginUserDO.Password != pwd {
		return "用户名或密码错误", data, nil
	}
	token := util2.Uuid32()
	data = &parameter.LoginRes{
		UserName:   loginUserDO.UserName,
		NickName:   loginUserDO.NickName,
		ExpiresIn:  consts.RedisCacheTimeTwoHour - 10,
		LoginToken: token,
	}
	redisKey := consts.RedisKeyUserToken + ":" + token
	util2.GetInstance().Put(token, loginUserDO.UserId)        //本地token缓存
	_, err = g.Redis().Set(ctx, redisKey, loginUserDO.UserId) //redis token缓存
	if err != nil {
		return "系统内部异常", data, err
	}
	_, err = g.Redis().Expire(ctx, redisKey, consts.RedisCacheTimeTwoHour) //设置token有效时间
	if err != nil {
		return "用户名或密码错误", data, nil
	}
	eeee, err := g.Redis().Get(ctx, redisKey)
	fmt.Println(gconv.String(eeee))
	return "OK", data, nil
}
